package com.example.smart.order.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * QR码信息工具类，提供生成和解析QR码的功能
 */
public final class QRCodeInfoUtils {

    // QR码图片保存路径
    private static final String QR_CODE_IMAGE_PATH = "E:\\QRCode\\";

    // 私有构造函数，防止实例化
    private QRCodeInfoUtils() {
    }

    /**
     * 生成QR码图片
     *
     * @param arg 包含QR码信息的参数对象
     * @return 生成的QR码图片文件路径
     */
    public static String generate(QRCodeInfo arg) {
        // 构建二维码数据，包含所有属性
        StringBuilder qrCodeData = new StringBuilder();
        qrCodeData.append("diningTableId=").append(arg.getDiningTableId());
        // 假设QRCodeInfo还有其他属性，例如：arg.getOtherProperty()
        // qrCodeData.append("&otherProperty=").append(arg.getOtherProperty());

        // 定义二维码图片文件路径
        String filePath = QR_CODE_IMAGE_PATH + "table_" + arg.getDiningTableId() + ".png";
        // 二维码图片大小
        int size = 200;
        // 二维码图片文件类型
        String fileType = "png";
        // 设置二维码参数
        Map<EncodeHintType, Object> hintMap = new HashMap<>();
        hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hintMap.put(EncodeHintType.MARGIN, 2);
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

        try {
            // 生成二维码
            BitMatrix matrix = new MultiFormatWriter().encode(qrCodeData.toString(), BarcodeFormat.QR_CODE, size, size, hintMap);
            Path path = FileSystems.getDefault().getPath(filePath);
            MatrixToImageWriter.writeToPath(matrix, fileType, path);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     * 解析QR码图片
     *
     * @param path QR码图片文件路径
     * @return 解析后的QR码信息对象
     */
    public static QRCodeInfo parse(String path) {
        QRCodeInfo qrCodeInfo = new QRCodeInfo();
        try {
            // 读取二维码图片
            BufferedImage bufferedImage = ImageIO.read(new File(path));
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
            // 解析二维码
            Result result = new MultiFormatReader().decode(binaryBitmap);
            String qrCodeData = result.getText();
            String[] pairs = qrCodeData.split("&");
            for (String pair : pairs) {
                String[] entry = pair.split("=");
                if (entry.length == 2) {
                    switch (entry[0]) {
                        case "diningTableId":
                            qrCodeInfo.setDiningTableId(Long.parseLong(entry[1]));
                            break;
                        // 假设QRCodeInfo还有其他属性，例如：otherProperty
                        // case "otherProperty":
                        //     qrCodeInfo.setOtherProperty(entry[1]);
                        //     break;
                    }
                }
            }
        } catch (IOException | ReaderException e) {
            e.printStackTrace();
        }
        return qrCodeInfo;
    }
}
